package com.taa.service.impl;

import com.taa.dao.IPaymentInfoDao;
import com.taa.dao.po.PaymentInfo;
import com.taa.dto.PaymentDTO;
import com.taa.enums.ResponseCode;
import com.taa.exception.AppException;
import com.taa.feign.OrderFeignClient;
import com.taa.response.Response;
import com.taa.service.IPaymentService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @Author: taa
 * @Desc: 支付服务实现类
 * @Create: 2025-06-22 19:20
 **/
@Slf4j
@Service
public class PaymentServiceImpl implements IPaymentService {

    @Resource
    private IPaymentInfoDao paymentInfoDao;

    @Resource
    private OrderFeignClient orderFeignClient;

    @Override
    @Transactional
    public Boolean processPayment(PaymentDTO paymentDTO) {
        // 1. 创建支付记录，初始状态为“待支付”
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderNo(paymentDTO.getOrderNo());
        paymentInfo.setAmount(paymentDTO.getAmount());
        paymentInfo.setStatus(0); // 0: 待支付
        int insertResult = paymentInfoDao.insert(paymentInfo);

        if (insertResult <= 0) {
            throw new AppException(ResponseCode.PAYMENT_FAILED.getCode(), "创建支付记录失败");
        }

        // --- 模拟支付成功 ---
        log.info("订单[{}] 模拟支付成功，开始处理后续流程...", paymentDTO.getOrderNo());

        // 2. 更新本地支付记录状态为“支付成功”
        int updateResult = paymentInfoDao.updateStatusByOrderNo(paymentDTO.getOrderNo(), 1); // 1: 支付成功
        if (updateResult <= 0) {
            throw new AppException(ResponseCode.PAYMENT_FAILED.getCode(), "更新支付记录状态失败");
        }

        // 3. 通过Feign调用，通知订单服务更新订单状态
        log.info("开始调用订单服务，更新订单[{}]的状态...", paymentDTO.getOrderNo());
        Response<Void> response = orderFeignClient.updateOrderStatus(paymentDTO.getOrderNo(), 1); // 1: 已支付

        // 4. 检查远程调用结果
        if (!Objects.equals(response.getCode(), ResponseCode.SUCCESS.getCode())) {
            // 如果远程调用失败，为了数据一致性，也抛出异常，让整个事务回滚
            log.error("远程调用订单服务更新状态失败, orderNo: {}, 原因: {}", paymentDTO.getOrderNo(), response.getInfo());
            throw new AppException(response.getCode(), "远程更新订单状态失败: " + response.getInfo());
        }

        log.info("订单[{}] 支付流程处理完毕！", paymentDTO.getOrderNo());
        return true;
    }
}

